//
//  UIImage++.swift
//  SwiftUI-WeChat
//
//  Created by Gesen on 2020/5/17.
//  Copyright © 2020 Gesen. All rights reserved.
//

import UIKit

extension UIImage {
    
    func withPadding(_ padding: UIEdgeInsets) -> UIImage {
        
        let adjustSizeForBetterHorizontalAlignment: CGSize = CGSize(
            width: size.width + padding.left + padding.right,
            height: size.height + padding.top + padding.bottom
        )
        
        let image: UIImage
        
        UIGraphicsBeginImageContextWithOptions(adjustSizeForBetterHorizontalAlignment, false, 0)
        draw(at: CGPoint(x: padding.left, y: padding.top))
        image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        
        return image
    }
    

    static func imageWithColor(_ color: UIColor) -> UIImage? {
        imageWithColor(color, size: CGSize(width: 1, height: 1))
    }
    
    static func imageWithColor(_ color: UIColor, size: CGSize) -> UIImage? {
        let renderer = UIGraphicsImageRenderer(size: size)
        let image = renderer.image { context in
            color.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }
        return image
    }

}


extension UIImage {
    convenience init(view: UIView) {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, UIScreen.main.scale)
        defer { UIGraphicsEndImageContext() }
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        guard let img = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
            self.init()
            return
        }
        self.init(cgImage: img)
    }
}


import Photos
extension UIImage {
    func saveToPhotoAlbum() {
        
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: self)
        }, completionHandler: { success, error in
            if let error = error {
//                    print("Error saving to photo album: \(error.localizedDescription)")
//                MBAProgressHUD.showErrorWithStatus("保存图片失败 \(error.localizedDescription)")
                MBAToast.show(text: "保存图片失败，请检查应用-设置是否打开权限",duration: 5)
            } else {
//                    print("Saved to photo album!")
//                MBAProgressHUD.showSuccessWithStatus("保存图片成功")
                MBAToast.show(text: "保存图片成功")
            }
        })
        
//        let image = self
//        let status = PHPhotoLibrary.authorizationStatus()
//        switch status {
//        case .authorized:
//            PHPhotoLibrary.shared().performChanges({
//                PHAssetChangeRequest.creationRequestForAsset(from: image)
//            }, completionHandler: { success, error in
//                if let error = error {
////                    print("Error saving to photo album: \(error.localizedDescription)")
//                    MBAProgressHUD.showErrorWithStatus("保存图片失败 \(error.localizedDescription)")
//                } else {
////                    print("Saved to photo album!")
//                    MBAProgressHUD.showSuccessWithStatus("保存图片成功")
//                }
//            })
//        case .denied, .restricted:
//            if let vc = MBAInfo.rootViewController(){
//                let alert = UIAlertController(title: "保存图片需访问相册", message: "请在应用设置中打开相册权限", preferredStyle: .alert)
//                let cancel = UIAlertAction(title: "取消", style: .cancel) { action in
//
//                }
//                let go =  UIAlertAction(title: "前往", style: .default) { action in
//                    UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
//                }
//                alert.addAction(cancel)
//                alert.addAction(go)
////                alert.addAction(UIAlertAction(title: "前往", style: .default))
//                vc.present(alert, animated: true)
//            }
//        case .notDetermined:
//            DispatchQueue.main.async {
//                PHPhotoLibrary.requestAuthorization { status in
//                    if status == .authorized {
////                        print("已授权")
//                    } else {
////                        print("未授权")
//                    }
//                }
//            }
//
//        case .limited:
//            break
//        @unknown default:
//            break
//        }
    }
}
